package com.czx.drivingtest.utils;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author czx
 * @date 2020/7/13 11:04
 */
public class HttpClientUtils {
    /**
     * 发送给请求，不带请求头
     * @param url
     * @param params 参数列表
     * @return
     * @throws IOException
     */
    public static String get(String url, List<NameValuePair> params) throws IOException {
        return get(url, params, null);
    }
    /**
     * 发送get请求，带请求头
     * @param url
     * @param params 参数列表
     * @param header 请求头
     * @return
     * @throws IOException
     */
    public static String get(String url, List<NameValuePair> params, Header header) throws IOException {
        String urlParams = "";
        if (CollectionUtil.isNotEmpty(params)) {
            urlParams = "?" + params.stream().map(p -> p.getName() + "=" + p.getValue()).collect(Collectors.joining("&"));
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
        HttpGet httpGet = new HttpGet(url + urlParams);
        httpGet.setConfig(requestConfig);
        httpGet.setHeader(header);
        try (CloseableHttpClient httpClient = getDefaultHttpClient();
             CloseableHttpResponse response = httpClient.execute(httpGet)){
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, StandardCharsets.UTF_8);
                }
            }
            return null;
        }
    }

    /**
     * 发送一个json格式的http请求，不带header
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String postJson(String url, String json) throws IOException {
        return postJson(url, json, null);
    }

    /**
     * 发送一个json格式的http请求
     * @param url
     * @param json
     * @param header
     * @return
     * @throws IOException
     */
    public static String postJson(String url, String json, Header header) throws IOException {
        //设置请求超时时间和传输超时时间为3秒钟
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
//        post.addHeader("Content-Type", "application/json");
        post.setHeader(header);
        StringEntity se = new StringEntity(json, StandardCharsets.UTF_8);
        se.setContentType("application/json");
        post.setEntity(se);

        try (CloseableHttpClient httpClient = getDefaultHttpClient();
             CloseableHttpResponse httpResponse = httpClient.execute(post)) {
            if (httpResponse != null ) {
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    HttpEntity entity = httpResponse.getEntity();
                    if (entity != null) {
                        return EntityUtils.toString(entity, StandardCharsets.UTF_8);
                    }
                }
            }
            return null;
        }
    }

    private static CloseableHttpClient getDefaultHttpClient() {
        return HttpClients.createDefault();
    }

    private static void closeHttpClient(CloseableHttpClient client) throws IOException {
        if (client != null) {
            client.close();
        }
    }
}
